package com.itheima.reggie.controller;

import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    //查询购物车数据
    @GetMapping("/list")
    public R<List> cartList() {
        Long userId = BaseContext.getCurrendId();
        List<ShoppingCart> shoppingCarts = shoppingCartService.cartList(userId);
        return R.success(shoppingCarts);
    }

    //添加菜品到购物车
    @PostMapping("/add")
    public R<ShoppingCart> addCart(@RequestBody ShoppingCart shoppingCart) {
        Long userId = BaseContext.getCurrendId();
        shoppingCart.setUserId(userId);
        shoppingCart.setCreateTime(LocalDateTime.now());
        ShoppingCart shoppingCart1 = shoppingCartService.addCart(shoppingCart);
        return R.success(shoppingCart1);
    }

    //清空购物车
    @DeleteMapping("/clean")
    public R<String> clearCart() {
        Long userId = BaseContext.getCurrendId();
        shoppingCartService.clearCart(userId);
        return R.success("清空成功");
    }

    //减少购物车菜品的数量
    @PostMapping("/sub")
    public R<ShoppingCart> updateCart(@RequestBody ShoppingCart shoppingCart) {
        Long userId = BaseContext.getCurrendId();
        shoppingCart.setUserId(userId);
        ShoppingCart shoppingCart1 = shoppingCartService.updateCart(shoppingCart);
        return R.success(shoppingCart1);
    }
}
